import QtQuick 1.1
//import com.nokia.symbian 1.1
import com.nokia.meego 1.0
import com.nokia.extras 1.1
import "UIConstants.js" as UI
import "platform.js" as PLATFORM
import NumismatMobile 1.0

Page {
    tools: commonTools

    Rectangle {
        anchors.fill: parent
        color: visual.colorBackgrond
    }

    Component {
        id: listDelegate

        Item {
            id: delegateItem
            width: listView.width
            height: UI.LIST_ITEM_HEIGHT_DEFAULT

            Row {
                spacing: 5
                anchors.verticalCenter: parent.verticalCenter
                Image {
                    id: coinImage
                    height: imgheight > UI.LIST_ITEM_HEIGHT_DEFAULT ? UI.LIST_ITEM_HEIGHT_DEFAULT : imgheight
                    width: imgwidth
                    source: "data:image/png;base64," + image
                    smooth: true
                    fillMode: Image.PreserveAspectFit
                }
                Column {
                    width: listView.width - coinImage.width - countBubble.width - 15
                    spacing: 5
                    Text {
                        text: title
                        width: parent.width
                        elide: Text.ElideRight
                        font.pixelSize: UI.FONT_DEFAULT
                        font.bold: true
                        color: UI.COLOR_FOREGROUND
                    }
                    Text {
                        function makeDescription() {
                            var desc = value + " " + unit;
                            if (year)
                                desc += ", " + year;
                            if (coinModel.view == CoinModel.CommemorativeWorld)
                                if (country)
                                    desc += ", " + country;
                            if (mintmark)
                                desc += ", " + mintmark;
                            if (mintage)
                                desc += ", " + qsTr("Mintage: ") + mintage;
                            if (series)
                                desc += ", " + series;
                            return desc
                        }

                        text: makeDescription()
                        width: parent.width
                        elide: Text.ElideRight
                        font.pixelSize: UI.FONT_SMALL
                        color: UI.COLOR_SECONDARY_FOREGROUND
                    }
                }
                CountBubble {
                    id: countBubble
                    visible: count > 0
                    value: count
                    largeSized: true
                }
            }

            MouseArea {
                anchors.fill: parent
                onClicked: {
                    detailsPage.coin = coinModel.get(index);
                    pageStack.push(detailsPage);
                }
                onPressed: {
                    listView.currentIndex = index;
                }
                onReleased: {
                    listView.currentIndex = -1;
                }
                onCanceled: {
                    listView.currentIndex = -1;
                }
                onPressAndHold: {
                    listMenu.coin = coinModel.get(index);
                    listMenu.index = index;
                    listMenu.count = count;
                    listMenu.open()
                }
            }
        }
    }

    Component {
        id: sectionHeading

        Rectangle {
            width: listView.width
            height: headerText.height
            color: "lightsteelblue"

            Item {
                anchors.fill: parent
                anchors.rightMargin: UI.DEFAULT_MARGIN
                anchors.leftMargin: UI.DEFAULT_MARGIN

                Text {
                    id: headerText
                    text: section
                    width: parent.width
                    horizontalAlignment: Text.AlignRight
                    font.pixelSize: UI.FONT_XSMALL
                    font.bold: true
                    color: UI.COLOR_SECONDARY_FOREGROUND
                }
            }
        }
    }

    ListView {
        id: listView
        width: parent.width
        anchors.top: viewHeader.bottom
        anchors.bottom: parent.bottom
        focus: true
        model: coinModel
        highlightFollowsCurrentItem: true
        currentIndex: -1
        delegate: listDelegate
        section.property: "year"
        section.criteria: ViewSection.FullString
        section.delegate: sectionHeading
        highlightMoveSpeed: -1
        highlight: BorderImage {
            source: visual.highlightBackground
            horizontalTileMode: BorderImage.Stretch
            verticalTileMode: BorderImage.Stretch
            width: listView.width
        }
    }

    ScrollDecorator {
        flickableItem: listView
    }

    ListModel {
        id: seriesModel
        function fill() {
            seriesModel.clear();
            for (var i in coinModel.seriesModel) {
                var series = coinModel.seriesModel[i];
                seriesModel.append({'name': series});
            }
            seriesSelectionDialog.selectedIndex = 0;
            seriesSelectionDialog.series = coinModel.seriesModel[0];
        }
    }

    property bool started: false
    onStatusChanged: {
        if (status === PageStatus.Active) {
            if (!started) {
                started = true;
                openDb(coinModel.lastCollection());
            }

            statusBar.text = coinModel.fileTitle()
        }
    }

    function openDb(newFile) {
        seriesModel.clear();
        openAction.file = newFile;
        openAction.start();
        listView.visible = false;
    }

    BusyAction {
        id: openAction
        text: qsTr("Loading...")
        property string file

        onWork: {
            if (status === PageStatus.Active) {
                openAction.stop();
                if (coinModel.open(file)) {
                    seriesModel.fill();
                    statusBar.text = coinModel.fileTitle()
                }
                else {
                    selectSource.open();
                }
                listView.visible = true;
            }
        }
    }

    function updateDb(newFile) {
        updateAction.file = newFile;
        updateAction.start();
        listView.visible = false;
    }

    BusyAction {
        id: updateAction
        text: qsTr("Updating...")
        subText: qsTr("It can take several minutes, don't interrupt it")
        property string file

        onWork: {
            if (status === PageStatus.Active) {
                updateAction.stop();
                if (coinModel.update(file)) {
                    seriesModel.fill();
                    statusBar.text = coinModel.fileTitle()
                }
                listView.visible = true;
            }
        }
    }

    SelectionDialog {
        id: seriesSelectionDialog
        titleText: coinModel.view === CoinModel.CommemorativeWorld ? qsTr("Select country") : qsTr("Select series")
        selectedIndex: 0
        model: seriesModel
        property string series: seriesModel.count ? coinModel.seriesModel[selectedIndex] : ''
        onAccepted: {
            series = coinModel.seriesModel[selectedIndex];
            seriesAction.start();
            listView.visible = false;
        }
    }

    BusyAction {
        id: seriesAction

        onWork: {
            coinModel.series = seriesSelectionDialog.selectedIndex;
            listView.visible = true;
        }
    }

    ViewHeader {
        id: viewHeader
        onClicked: seriesSelectionDialog.open()
        titleText: seriesSelectionDialog.series
        iconSource: PLATFORM.TYPE === "harmattan" ?
                        "image://theme/icon-m-textinput-combobox-arrow" :
                        privateStyle.imagePath("qtg_graf_choice_list_indicator", false)
    }

    Menu {
        id: listMenu
        property variant coin
        property int index
        property int count

        MenuLayout {
            MenuItem {
                text: qsTr("Add")
                onClicked: {
                    var posY = listView.contentY;
                    coinModel.clone(listMenu.index);
                    listView.contentY = posY;
                }
            }
            MenuItem {
                text: qsTr("Delete")
                enabled: listMenu.count > 0

                onClicked: {
                    deleteConfirmation.coin = listMenu.coin;
                    deleteConfirmation.index = listMenu.index;
                    deleteConfirmation.open();
                }
            }
        }
    }

    QueryDialog {
        id: deleteConfirmation
        property variant coin
        property int index

        titleText: qsTr("Delete the coin from collection?")
        message: deleteConfirmation.coin ? deleteConfirmation.coin.title : ''
        acceptButtonText: qsTr("Yes")
        rejectButtonText: qsTr("No")

        onAccepted: {
            var posY = listView.contentY;
            coinModel.remove(deleteConfirmation.index)
            listView.contentY = posY;
        }
    }

    QueryDialog {
        id: selectSource

        titleText: qsTr("Select collection")
        message: qsTr("Where from get collection for working?")
        acceptButtonText: qsTr("Download from web")
        rejectButtonText: qsTr("Open existen")

        onAccepted: pageStack.push(downloadPage);
        onRejected: {
            fileDialog.folder = 'file:///'+coinModel.folder();
            pageStack.push(fileDialog);
        }
    }
}
